#include "clientsocket.h"

ClientSocket::ClientSocket ( std::string host, int port )
{
    BaseSocket::create();
    BaseSocket::connect(host, port);
}

bool ClientSocket::sendFile(const std::string& path) const
{
    std::ifstream input(path.c_str(), std::ios::binary);
    std::string msg;
    char byte;
    unsigned long int size;
    std::ostringstream stringsize;

    if (!input.good() || input.eof() || !input.is_open())
    {
        return false;
    }
    input.seekg(0, std::ios_base::beg);
    std::ifstream::pos_type begin_pos = input.tellg();
    input.seekg(0, std::ios_base::end);
    size = static_cast<unsigned long int>(input.tellg() - begin_pos);

    input.seekg(0, std::ios_base::beg);

    stringsize << size;

    operator<<(stringsize.str());
    operator>>(msg);

    unsigned long int i=0;
    while(i<size)
    {
        input.read(&byte, sizeof(char));

        if (!sendBlock(byte))
            return false;
        i++;
    }

    return true;
}

int ClientSocket::recvFile(const std::string& path)
{
    std::ofstream output(path.c_str(), std::ios::binary);
    std::string msg, tmpsize;
    char byte;
    unsigned long int size, i;
    std::istringstream stringsize;
    int status=0;

    operator>>(tmpsize);
    stringsize.str(tmpsize);
    stringsize >> size;

    operator<<("ok");

    if (output.good())
    {
        for (i=0; i<size; i++)
        {
            if((status = recvBlock(byte)) == -1)
            {
                std::cout << "status -1 dans ClientSocket::recvFile" << std::endl;
                return -1;
            }
            output.write(&byte, sizeof(char));
        }
    }
    return status;
}

const ClientSocket& ClientSocket::operator << (const std::string& s) const
{
    BaseSocket::send(s);
    return *this;
}

const ClientSocket& ClientSocket::operator >> (std::string& s) const
{
    BaseSocket::recv(s);
    return *this;
}
